package com.bookmanagement.interceptor;

import com.bookmanagement.properties.JwtProperties;
import com.bookmanagement.utils.BaseContext;
import com.bookmanagement.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author skyjay
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        log.info("请求方法：{}", method);
        // 如果不是映射到方法直接通过
        if((!(handler instanceof HandlerMethod))){
            return true;
        }

        String token = request.getHeader(jwtProperties.getUserTokenName());
        try {
            String email = JwtUtil.getEmail(token, jwtProperties.getUserSecretKey());
            log.info("用户邮箱：{}", email);
            BaseContext.setCurrentId(email);
            return true;
        }
        catch (Exception e){
            log.error("用户认证失败！token={}",e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

    }
}
